#!/usr/bin/env node

const{URLSearchParams} = require('url');
const db = require('./db.js');

const http = require('http'),
      log = console.log;

http.createServer(async (req, res) => {
    log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
    switch(req.method) {
        case 'GET':
          await select(req,res);
          break
        case 'PUT':
          res.end('put')
          break;
        case 'POST':
          insert(req,res)
          break;
        case 'DELETE':
          res.end('delete');
          break;
        default:
          res.end('request method not support');
  }
}).listen(8080);

async function select(req,res){
  res.setHeader('Access-Control-Allow-Origin', '*');
  const items = await db.getItems();
  res.end(items);
}

function insert(req,res){
  res.setHeader('Access-Control-Allow-Origin', '*');
  let item = '';
  req.on('data',chunk=>item+=chunk);
  req.on('end',async ()=>{
    item = new URLSearchParams(item);
    item = item.get('item');
    if(item!==''||
      typeof item !== 'undefined'){
      await db.insert(item);
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.end('insert ok!');
    } else {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.end('items empty');
    }
  });
}



